package com.ruoyi.web.controller.biz;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.biz.domain.DormitoryBaseInfo;
import com.ruoyi.biz.domain.PersonalInfo;
import com.ruoyi.biz.service.DormitoryBaseInfoService;
import com.ruoyi.biz.service.IPersonalInfoService;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 入住人员信息Controller
 *
 * @author ruoyi
 * @date 2024-09-10
 */
@RestController
@RequestMapping("/biz/personalinfo")
public class PersonalInfoController extends BaseController {
    @Autowired
    private IPersonalInfoService personalInfoService;
    @Autowired
    private DormitoryBaseInfoService dormitoryBaseInfoService;

    /**
     * 查询入住人员信息列表
     */
    @PreAuthorize("@ss.hasPermi('biz:personal:list')")
    @GetMapping("/list")
    public TableDataInfo list(PersonalInfo personalInfo) {
        startPage();
        List<PersonalInfo> list = personalInfoService.selectPersonalInfoList(personalInfo);
        return getDataTable(list);
    }

    /**
     * 导出入住人员信息列表
     */
    @PreAuthorize("@ss.hasPermi('biz:personal:export')")
    @Log(title = "入住人员信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PersonalInfo personalInfo) {
        List<PersonalInfo> list = personalInfoService.selectPersonalInfoList(personalInfo);
        ExcelUtil<PersonalInfo> util = new ExcelUtil<PersonalInfo>(PersonalInfo.class);
        util.exportExcel(response, list, "入住人员信息数据");
    }

    /**
     * 获取入住人员信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('biz:personal:query')")
    @GetMapping(value = "/{personalId}")
    public AjaxResult getInfo(@PathVariable("personalId") Long personalId) {
        return success(personalInfoService.selectPersonalInfoByPersonalId(personalId));
    }

    /**
     * 新增入住人员信息
     */
    @PreAuthorize("@ss.hasPermi('biz:personal:add')")
    @Log(title = "入住人员信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PersonalInfo personalInfo) {
        //入住人员唯一校验
        PersonalInfo info = new PersonalInfo();
        info.setPersonalIdCard(personalInfo.getPersonalIdCard());
        List infoList = personalInfoService.selectPersonalInfoList(info);
        if (StringUtils.isNotEmpty(infoList) && infoList.size() > 0) {
            throw new RuntimeException("[" + personalInfo.getPersonalName() + "]人员已存在");
        } else {
            //宿舍入住人数校验
            if (StringUtils.isNotEmpty(personalInfo.getDormitoryCode())) {
                DormitoryBaseInfo dormitoryBaseInfo = new DormitoryBaseInfo();
                dormitoryBaseInfo.setDormitoryCode(personalInfo.getDormitoryCode());
                List<DormitoryBaseInfo> dormitoryBaseInfoList = dormitoryBaseInfoService.selectDormitoryBaseInfoList(dormitoryBaseInfo);
                if (StringUtils.isNotEmpty(dormitoryBaseInfoList) && dormitoryBaseInfoList.size() > 0) {
                    dormitoryBaseInfo = dormitoryBaseInfoList.get(0);
                    if (1L == dormitoryBaseInfo.getDormitoryStatus()) {
                        //使用中
                        Long maxNum = dormitoryBaseInfo.getDormitoryMaxNum();
                        if (null != maxNum && maxNum > 0) {
                            int num = dormitoryBaseInfo.getDormitoryOccupancy().intValue() + 1;
                            if (maxNum.compareTo(Long.valueOf(num)) == -1) {
                                throw new RuntimeException("宿舍[" + personalInfo.getDormitoryCode() + "]超出入住人员上限,入住失败");
                            } else {
                                //更新宿舍入住人数
                                dormitoryBaseInfo.setDormitoryOccupancy(Long.valueOf(num));
                                dormitoryBaseInfoService.updateDormitoryBaseInfo(dormitoryBaseInfo);
                            }
                        }
                    } else {
                        //高级干部间-预定中 更新宿舍状态
                        dormitoryBaseInfo.setDormitoryStatus(1L);
                        dormitoryBaseInfoService.updateDormitoryBaseInfo(dormitoryBaseInfo);
                    }
                } else {
                    throw new RuntimeException("宿舍[" + personalInfo.getDormitoryCode() + "]不存在或未启用");
                }
            }
        }


        return toAjax(personalInfoService.insertPersonalInfo(personalInfo));
    }

    /**
     * 修改入住人员信息
     */
    @PreAuthorize("@ss.hasPermi('biz:personal:edit')")
    @Log(title = "入住人员信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PersonalInfo personalInfo) {
        //新旧状态变更
        PersonalInfo info = personalInfoService.selectPersonalInfoByPersonalId(personalInfo.getPersonalId());

        Long personalStatus = personalInfo.getPersonalStatus();
        if (personalStatus != info.getPersonalStatus()) {
            //0-已退住 1-已入住 2-已申请
            if ("0".equals(personalInfo.getPersonalStatus())) {

            }
            if (StringUtils.isNotEmpty(personalInfo.getDormitoryCode())) {

            }
        } else {
            /*当人员入住状态一致*/
            String dormitoryCode = personalInfo.getDormitoryCode();
            String dormitory = info.getDormitoryCode();
            if (StringUtils.isEmpty(dormitoryCode)) {
                if (StringUtils.isNotEmpty(dormitory)) {
                    DormitoryBaseInfo dormitoryBaseInfo = new DormitoryBaseInfo();
                    dormitoryBaseInfo.setDormitoryCode(dormitory);
                    List<DormitoryBaseInfo> dormitoryBaseInfoList = dormitoryBaseInfoService.selectDormitoryBaseInfoList(dormitoryBaseInfo);

                }
            } else {

            }

        }

        return toAjax(personalInfoService.updatePersonalInfo(personalInfo));
    }

    /**
     * 删除入住人员信息
     */
    @PreAuthorize("@ss.hasPermi('biz:personal:remove')")
    @Log(title = "入住人员信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{personalIds}")
    public AjaxResult remove(@PathVariable Long[] personalIds) {
        List<Long> longList = Arrays.stream(personalIds).collect(Collectors.toList());
        for (int i = 0; i < personalIds.length; i++) {
            //释放宿舍人数
            PersonalInfo personalInfo = personalInfoService.selectPersonalInfoByPersonalId(longList.get(i));

            DormitoryBaseInfo dormitoryBaseInfo = new DormitoryBaseInfo();
            dormitoryBaseInfo.setDormitoryCode(personalInfo.getDormitoryCode());
            List<DormitoryBaseInfo> dormitoryBaseInfoList = dormitoryBaseInfoService.selectDormitoryBaseInfoList(dormitoryBaseInfo);
            if (null != dormitoryBaseInfoList && !dormitoryBaseInfoList.isEmpty()) {
                dormitoryBaseInfo = dormitoryBaseInfoList.get(0);
                long occupancy = 0L;
                long dormitoryOccupancy = dormitoryBaseInfo.getDormitoryOccupancy();
                if (!Objects.isNull(dormitoryOccupancy) && dormitoryOccupancy > 0) {
                    occupancy = dormitoryOccupancy - 1;
                    dormitoryBaseInfo.setDormitoryOccupancy(occupancy);
                    dormitoryBaseInfoService.updateDormitoryBaseInfo(dormitoryBaseInfo);
                }
            }
        }

        return toAjax(personalInfoService.deletePersonalInfoByPersonalIds(personalIds));
    }
}
